<template>
  <div
    id="mapContainerid"
    ref="mapContainer"
    style="display: flex; flex-direction: row; flex: 1"
  ></div>
</template>

<script setup>
// import { getMapData } from "@/api/statistics/indexStatistic";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import anhuiGeoJSON from "@/assets/geojson/anhui.json";
import hefeiGeoJSON from "@/assets/geojson/hefei.json";
import anqingGeoJSON from "@/assets/geojson/anqing.json";
import bengbuGeoJSON from "@/assets/geojson/bengbu.json";
import fuyangGeoJSON from "@/assets/geojson/fuyang.json";
import haozhouGeoJSON from "@/assets/geojson/haozhou.json";
import huaibeiGeoJSON from "@/assets/geojson/huaibei.json";
import huainanGeoJSON from "@/assets/geojson/huainan.json";
import huangshanGeoJSON from "@/assets/geojson/huangshan.json";
import liuanGeoJSON from "@/assets/geojson/liuan.json";
import maanshanGeoJSON from "@/assets/geojson/maanshan.json";
import suzhouGeoJSON from "@/assets/geojson/suzhou.json";
import tonglingGeoJSON from "@/assets/geojson/tongling.json";
import wuhuGeoJSON from "@/assets/geojson/wuhu.json";
import xuanchengGeoJSON from "@/assets/geojson/xuancheng.json";
import chuzhouGeoJSON from "@/assets/geojson/chuzhou.json";
import chizhouGeoJSON from "@/assets/geojson/chizhou.json";
import markIcon1 from "@/assets/images/mark-1.png";
import markIcon2 from "@/assets/images/mark-2.png";
import markIcon3 from "@/assets/images/mark-3.png";
import markIconDt from "@/assets/images/mark-dt.png";
import { onMounted, onUnmounted, reactive, useTemplateRef, watch } from "vue";
import { ref } from "vue";
import { toRefs } from "vue";
import { listQy } from "@/api/home";
import { listJyz } from "@/api/home";
import { handleTree } from "@/utils/tree";

defineOptions({ name: "AnhuiMap" });
const emits = defineEmits(["unit-name-changed"]);

const props = defineProps({
  unitname: {
    type: String,
  },
});
const { unitname } = toRefs(props);

let map = ref();
let geojson = ref();
let date = ref();
let zoom = ref(6);
let dsZoom = ref(9);
let centerPoint = ref([]);
let whiteOverlay = ref();
let resizeObserver = ref();
let tooltipData = ref([]);
let markerGroup = ref();
onMounted(() => {
  setMapParams();
  selectMapData();
});
watch(tooltipData, () => {
  initMap();
  observeMapContainer();
});
let unitName = ref("");
watch(unitName, () => {
  emits("unit-name-changed", unitName.value);
});

async function selectMapData() {
  // getMapData({ unitName: this.unitname }).then((res) => {
  //   this.tooltipData = res.data;
  // });
  let treeData = [];
  let data = [];
  let qyRes = await listQy();
  let qyRows = qyRes.data;
  for (let row of qyRows) {
    data.push({ id: row.id, parentId: row.parentId, name: row.qymc });
  }

  let jyzRes = await listJyz({ pageNum: 1, pageSize: 1000 });
  let jyzRows = jyzRes.rows;

  for (let row of jyzRows) {
    data.push({ id: row.id, parentId: row.qyId, name: row.jyzmc, leaf: true });
  }
  treeData = handleTree(data);
  //第一级是省
  tooltipData.value = [];
  for (let tree of treeData[0].children) {
    let num1 = 0;
    if (tree.children) {
      for (let tree2 of tree.children) {
        if (tree2.children) {
          num1 += tree2.children.length;
        }
      }
    }
    tooltipData.value.push({ name: tree.name, num1: num1, num2: "0" });
  }
}
function setMapParams() {
  //拿到用户所属地市信息，根据更具地市信息加载不同的地图
  if (unitname.value === "安徽省") {
    geojson.value = anhuiGeoJSON;
    centerPoint.value = [32.06, 117.28];
    zoom.value = 7;
    // this.unitName = '安徽省';
  } else if (unitname.value === "合肥市") {
    geojson.value = hefeiGeoJSON;
    centerPoint.value = [31.79, 117.28];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "安庆市") {
    geojson.value = anqingGeoJSON;
    centerPoint.value = [30.59, 116.48];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "蚌埠市") {
    geojson.value = bengbuGeoJSON;
    centerPoint.value = [33.1, 117.28];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "阜阳市") {
    geojson.value = fuyangGeoJSON;
    centerPoint.value = [33.1, 115.8];
    zoom.value = dsZoom.value;

    //32.79 变大向下  115.68 变大向左
  } else if (unitname.value === "亳州市") {
    geojson.value = haozhouGeoJSON;
    centerPoint.value = [33.6, 116.08];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "淮北市") {
    geojson.value = huaibeiGeoJSON;
    centerPoint.value = [33.79, 116.98];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "淮南市") {
    geojson.value = huainanGeoJSON;
    centerPoint.value = [32.59, 116.88];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "黄山市") {
    geojson.value = huangshanGeoJSON;
    centerPoint.value = [29.99, 118.08];
    zoom.value = thdatais.dsZoom;
  } else if (unitname.value === "六安市") {
    geojson.value = liuanGeoJSON;
    centerPoint.value = [31.79, 116.38];
    zoom.value = 8;
  } else if (unitname.value === "马鞍山市") {
    geojson.value = maanshanGeoJSON;
    centerPoint.value = [31.79, 118.38];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "宿州市") {
    geojson.value = suzhouGeoJSON;
    centerPoint.value = [34.1, 117.13];
    zoom.value = 8;
  } else if (unitname.value === "铜陵市") {
    geojson.value = tonglingGeoJSON;
    centerPoint.value = [30.9, 117.63];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "芜湖市") {
    geojson.value = wuhuGeoJSON;
    centerPoint.value = [31.3, 118.03];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "宣城市") {
    geojson.value = xuanchengGeoJSON;
    centerPoint.value = [30.7, 118.81];
    zoom.value = dsZoom.value;
  } else if (unitname.value === "滁州市") {
    geojson.value = chuzhouGeoJSON;
    centerPoint.value = [32.7, 118.09];
    zoom.value = 9;
  } else if (unitname.value === "池州市") {
    geojson.value = chizhouGeoJSON;
    centerPoint.value = [30.3, 117.39];
    zoom.value = tdatahis.dsZoom;
    // }else{
    //   this.geojson = anhuiGeoJSON;
    //   this.centerPoint = [31.86, 118.28]
    //   this.zoom = 6;
  }
}
function addWhiteOverlay() {
  // 2. 添加全屏白色覆盖层
  const southWest = L.latLng(-10, 60); // 西南角（更精确）
  const northEast = L.latLng(60, 150); // 东北角（更精确）
  whiteOverlay.value = L.rectangle([southWest, northEast], {
    fillColor: "#fff",
    fillOpacity: 0.9,
    weight: 0,
  }).addTo(map.value);
  whiteOverlay.value.bringToBack();
}
function observeMapContainer() {
  const mapContainer = document.getElementById("mapContainerid");
  if (mapContainer) {
    resizeObserver.value = new ResizeObserver(() => {
      map.value.invalidateSize();
      updateWhiteOverlay();
    });
    resizeObserver.value.observe(mapContainer);
  }
}
function updateWhiteOverlay() {
  if (whiteOverlay.value) {
    map.value.removeLayer(whiteOverlay.value);
  }
  addWhiteOverlay();
}
let mapContainer = useTemplateRef("mapContainer");
function initMap() {
  // this.setMapParams();
  // 初始化地图
  map.value = L.map(mapContainer.value, {
    zoomControl: false,
  }).setView(centerPoint.value, zoom.value);
  // 添加天地图影像底图
  L.tileLayer(
    "http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
      "&tk=ebbb7e8a32c07416a391b431ee053a8e",
    {
      attribution: "",
    }
  ).addTo(map.value);
  // 添加天地图影像底图
  // L.tileLayer('https://api.idp.ah.cegn.cn/skdz/skdz/api/gmap/rest/5416BB9217/skdz/tdt/vec_w/wmts?key=684042254650576896', {
  //   attribution: ''
  // }).addTo(this.map);

  // 添加安徽省GeoJSON图层
  addAnhuiGeoJsonLayer();
}

function addAnhuiGeoJsonLayer() {
  // 创建默认图标
  const defaultIcon = L.icon({
    iconUrl: markIcon3,
    iconSize: [13, 13],
    iconAnchor: [10, 15],
    popupAnchor: [0, -32],
  });
  // 创建高亮图标
  const highlightedIcon = L.icon({
    iconUrl: markIconDt,
    iconSize: [40, 40],
    iconAnchor: [15, 30],
  });
  // 定义图标
  const getIcon = (value) => {
    return value === unitName.value ? highlightedIcon : defaultIcon;
  };

  // 存储所有标记的组，方便后续管理
  markerGroup.value = L.layerGroup().addTo(map.value);
  // 2. 添加全屏白色覆盖层
  const southWest = L.latLng(-10, 60); // 西南角（更精确）
  const northEast = L.latLng(60, 150); // 东北角（更精确）
  whiteOverlay.value = L.rectangle([southWest, northEast], {
    fillColor: "#fff",
    fillOpacity: 0.9,
    weight: 0, // 移除边框
  }).addTo(map.value);
  // 单独渲染外围边界（加粗）
  const outlineLayer = L.geoJSON(geojson.value, {
    style: () => ({
      color: "#8abdfd", // 深蓝色，突出边界
      weight: 6, // 加粗
      opacity: 1,
      fill: false, // 不填充，仅描边
    }),
  }).addTo(map.value);
  const geojsonLayer = L.geoJSON(geojson.value, {
    style: (feature) => {
      return {
        // interactive: false, // 禁用交互样式
        color: "#8abdfd",
        weight: 0,
        opacity: 1,
        fillColor: "#d1e3f8",
        fillOpacity: 0.9,
      };
    },
    onEachFeature: (feature, layer) => {
      if (feature.properties && feature.properties.name) {
        // layer.bindPopup(feature.properties.name);
        // 计算多边形的中心点，用于放置标签
        const bounds = layer.getBounds();
        const center = bounds.getCenter();

        // 添加标记
        const marker = L.marker(center, {
          icon: defaultIcon,
          // title: feature.properties.name
        }).addTo(map.value);
        // // 存储标记以便后续更新
        // this.markers[feature.properties.name] = marker;

        const date = tooltipData.value.find(
          (t) => t.name === feature.properties.name
        );

        // 动态生成 Tooltip
        const tooltipContent = `
                <div class="custom-map-tooltip">
                  <div class="tooltip-left">
                    <span class="tooltip-icon">
                      <img src="${markIcon1}" width="12" height="12">
                    </span>
                    <span class="tooltip-number">${date ? date.num1 : 0}</span>
                  </div>
                  <div class="tooltip-divider"></div>
                  <div class="tooltip-right">
                    <img src="${markIcon2}" width="12" height="12">
                    <span class="tooltip-number">${date ? date.num2 : 0}</span>
                  </div>
                </div>
              `;
        // 绑定提示框
        marker.bindTooltip(tooltipContent, {
          sticky: false, // 提示框跟随鼠标
          direction: "top", // 显示在标记上方
          permanent: true, // 关键选项：永久显示
          className: "custom-map-tooltip-container",
          offset: [0, -20], // 向上移动 10 像素（Y 轴负方向
        });

        // 添加标签
        L.tooltip({
          content: feature.properties.name,
          permanent: true, // 永久显示
          direction: "center",
          className: "city-label-my",
        })
          .setLatLng(center)
          .addTo(map.value);
        // 为 GeoJSON 图层添加点击事件
        layer.on(
          "click",
          (e) => {
            // if (process.env.VUE_APP_UNITNAME === "安徽省") {
            unitName.value = feature.properties.name;
            // }
          },
          { once: true }
        );
      }
    },
  }).addTo(map.value);
  geojsonLayer.setZIndex(5); // 原始边界
}

onUnmounted(() => {
  if (map.value) {
    map.value.remove();
    map.value = null;
  }
  if (resizeObserver.value) {
    resizeObserver.value.disconnect();
  }
});
</script>

<style>
/* 移除所有元素的 outline */
* {
  outline: none;
}
.leaflet-control-attribution {
  display: none !important;
}
.leaflet-container {
  background-color: white !important;
}
.city-label-my {
  background-color: transparent !important; /* 强制背景色为全透明 */
  border: none !important; /* 强制移除边框 */
  box-shadow: none !important; /* 强制移除阴影 */
  font-size: 13px !important; /* 字体大小 */
  font-weight: bold !important; /* 字体加粗 */
  color: #3d4e59 !important; /* 字体颜色 */
  padding: 0 !important; /* 强制移除内边距 */
  border-radius: 0 !important; /* 强制移除圆角 */
  outline: none !important; /* 移除轮廓 */
  text-shadow: none !important; /* 移除文本阴影 */
}
.label-my {
  background-color: #ffffff;
  font-size: 12px;
  font-weight: bold;
  color: #0062ff;
}

/* 外部容器：白色背景 + 圆角 + 阴影 */
.custom-map-tooltip-container.leaflet-tooltip {
  background: transparent !important; /* 移除 Leaflet 默认背景 */
  padding: 0 !important; /* 移除默认内边距 */
  box-shadow: none !important; /* 移除默认阴影 */
  border: none !important; /* 移除边框 */
}

/* 自定义 Tooltip 主体 */
.custom-map-tooltip {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 30px; /* 圆角 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); /* 轻微阴影 */
  padding: 6px 12px; /* 内边距 */
  font-size: 10px;
  white-space: nowrap;
}

/* 左侧部分（定位图标 + 数字） */
.tooltip-left {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 右侧部分（柱状图图标 + 数字） */
.tooltip-right {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 图标样式 */
.tooltip-icon {
  font-size: 10px;
}

/* 数字样式 */
.tooltip-number {
  font-weight: bold;
}

/* 分隔线（竖线） */
.tooltip-divider {
  width: 1px;
  height: 13px;
  background: #e0e0e0;
  margin: 0 8px;
}
</style>
